﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Charades.Web.Helpers;
using Charades.Web.Server.User;
using Elmah;

namespace Charades.Web.Server.Room
{
	using System.Configuration;

	using Charades.Web.Server.Round;

	public class RoomHandler
	{
		private UserHandler _userHandler;
		private object _locker;
		private ConcurrentDictionary<string, Room> _roomList;

		private readonly int MaxRoomSize = int.Parse(ConfigurationManager.AppSettings.Get("MaxRoomSize"));
		private readonly int MinRoomSize = int.Parse(ConfigurationManager.AppSettings.Get("MinRoomSize"));

		public RoomHandler(UserHandler userHandler, object locker)
		{
			_userHandler = userHandler;
			_locker = locker;
			_roomList = new ConcurrentDictionary<string, Room>();
		}

		public Room FindRoomForNewUser()
		{
			var room = _roomList.OrderBy(r => r.Value.Users.Count).FirstOrDefault(r => r.Value.Users.Count > 0 && r.Value.Users.Count < MaxRoomSize && r.Value.Status != RoomStatus.Finished).Value;
			if (room == null)
			{
				room = new Room();
				_roomList.TryAdd(room.Id, room);
				ErrorLog.GetDefault(null).Log(new Error(new Exception(String.Format("Новая комната создана. Всего {0} комнат запущено.", _roomList.Count))));
				RoomCreatingTimer.StartTimer();
			}

			return room;
		}

		public Room GetRoom(string connectionId)
		{
			return _roomList.OrderByDescending(r => r.Value.Date).FirstOrDefault(r => r.Value.Users.Any(u => u.ConnectionId == connectionId)).Value;
		}

		public void RemoveUser(string connectionId)
		{
			var room = GetRoom(connectionId);
			if (room != null)
			{
				var user = room.Users.First(u => u.ConnectionId == connectionId);
				room.Users.Remove(user);
				if (room.Users.Count < MinRoomSize)// < потому что данный пользователь уже удален
				{
					_roomList.TryRemove(room.Id, out room);
					room.Status = RoomStatus.Finished;
				}
			}
		}

		public bool UserCanDraw(string connectionId)
		{
			var result = false;
			var room = this.GetRoom(connectionId);
			if (room != null)
			{
				var round = room.Rounds.FirstOrDefault(r => r.User.ConnectionId == connectionId && r.State == RoundState.Started);
				if (round != null)
				{
					result = true;
				}
			}
			return result;
		}
	}
}